/*
 * author      : dormi330
 * date        : 2018/7/16
 * description : TODO
 */

package com.deep.trade.adaptor.required.mq.nats;

import com.deep.trade.adaptor.required.mq.MsgReceiver;
import com.deep.trade.adaptor.required.mq.UniqueMessageHandler;
import com.deep.trade.common.BaseMssage;
import com.deep.trade.common.CommonUtils;
import io.nats.client.Connection;
import io.nats.client.Message;
import io.nats.client.MessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
public class NatsMsgReceiver implements MsgReceiver {

    @Autowired
    private Connection natsConnection;

    public void register(String topic, UniqueMessageHandler uniqueMessageHandler) {
        natsConnection.subscribe(topic, new MessageHandler() {
            @Override
            public void onMessage(Message msg) {

            }
        });

        natsConnection.subscribe(topic, messageHandler(uniqueMessageHandler));
    }

    // 将 UniqueMessageHandler 适配成 MessageHandler
    private MessageHandler messageHandler(UniqueMessageHandler uniqueMessageHandler) {
        return msg -> {
            BaseMssage baseMssage = null;
            try {
                String msgData = new String(msg.getData(), "UTF-8");
                baseMssage = CommonUtils.fromJsonString(msgData, BaseMssage.class);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            uniqueMessageHandler.handle(baseMssage);
        };
    }
}
